import React, { Component } from 'react'
import styles from './index.module.scss'

class HousePackage extends Component {
    state = {
        // 选中名称
        selectedNames: [],
       // 所有房屋配置项
 HOUSE_PACKAGE: [
    {
      id: 1,
      name: '衣柜',
      icon: 'icon-wardrobe'
    },
    {
      id: 2,
      name: '洗衣机',
      icon: 'icon-wash'
    },
    {
      id: 3,
      name: '空调',
      icon: 'icon-air'
    },
    {
      id: 4,
      name: '天然气',
      icon: 'icon-gas'
    },
    {
      id: 5,
      name: '冰箱',
      icon: 'icon-ref'
    },
    {
      id: 6,
      name: '暖气',
      icon: 'icon-Heat'
    },
    {
      id: 7,
      name: '电视',
      icon: 'icon-vid'
    },
    {
      id: 8,
      name: '热水器',
      icon: 'icon-heater'
    },
    {
      id: 9,
      name: '宽带',
      icon: 'icon-broadband'
    },
    {
      id: 10,
      name: '沙发',
      icon: 'icon-sofa'
    }
]
      }
    toggleSelect = name => {
        const { selectedNames } = this.state
        let newSelectedNames
        console.log(selectedNames.indexOf(name));
        if(selectedNames.indexOf(name) > -1){
          // 选中：从数组中删除选中项，也就是保留未选中项
          newSelectedNames = selectedNames.filter(item => item !== name) 
        } else {
         // 未选中：添加到数组中
          newSelectedNames = [...selectedNames, name]
          console.log(newSelectedNames);
        }
         // 传递给父组件
        this.props.onSelect(newSelectedNames)
    
        this.setState({
            selectedNames: newSelectedNames
        })
      }
      renderItems = () => {
        const { selectedNames,HOUSE_PACKAGE } = this.state
        return (
                HOUSE_PACKAGE.map(item => (
                // 判断该项是否选中
                //  <li key={item.id}  className={[styles.item, selectedNames.indexOf(item.name) > -1 ? styles.active : ''].join(' ')} onClick={this.toggleSelect(item.name)}>
                 <li key={item.id}  className={[styles.item, selectedNames.indexOf(item.name) > -1 ? styles.active : ''].join(' ')} onClick={()=>this.toggleSelect(item.name)}>
                    <p> <i className={`iconfont ${item.icon} ${styles.icon}`} /></p>
                    {item.name}
                 </li>
                ))   
        )
    }
    render() {
       return (
        <ul className={styles.roos}>
            {this.renderItems()}
        </ul>
       )
    }
  }
  
// 属性默认值，防止在使用该组件时，不传 onSelect 报错
HousePackage.defaultProps = {
    onSelect: () => {}
}
export default HousePackage
